<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工业物联网数据采集系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .header {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 20px 0;
            text-align: center;
            color: white;
            margin-bottom: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        h1 {
            margin: 0;
            font-size: 2.5em;
            font-weight: 300;
        }
        
        .dashboard {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .status-panel {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .status-card {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 20px;
            margin: 15px 0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .status-icon {
            font-size: 2em;
        }
        
        .function-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        
        .function-btn {
            background: white;
            border: none;
            border-radius: 12px;
            padding: 25px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-decoration: none;
            color: #333;
            display: block;
        }
        
        .function-btn:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .function-btn .icon {
            font-size: 3em;
            margin-bottom: 10px;
            display: block;
        }
        
        .function-btn h3 {
            margin: 10px 0 5px 0;
            color: #333;
        }
        
        .function-btn p {
            margin: 0;
            color: #666;
            font-size: 0.9em;
        }
        
        .content-area {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            margin-top: 20px;
            min-height: 400px;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .error {
            background: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #f44336;
        }
        
        .device-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
            border-left: 4px solid #007bff;
        }
        
        .device-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: bold;
        }
        
        .status-connected {
            background: #d4edda;
            color: #155724;
        }
        
        .status-disconnected {
            background: #f8d7da;
            color: #721c24;
        }
        
        .hidden {
            display: none;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        
        .metric {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 10px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 6px;
        }
        
        .metric-value {
            font-weight: bold;
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>工业物联网数据采集系统</h1>
            <p>Industrial IoT Data Collection System</p>
        </div>
    </div>
    
    <div class="container">
        <div class="dashboard">
            <!-- 左侧状态面板 -->
            <div class="status-panel">
                <h2>系统状态</h2>
                <div id="system-status" class="status-card">
                    <div>
                        <div class="status-icon">🟢</div>
                    </div>
                    <div>
                        <h3>系统运行正常</h3>
                        <p>所有服务已启动</p>
                    </div>
                </div>
                
                <div class="metric">
                    <span>在线设备</span>
                    <span id="online-devices" class="metric-value">--</span>
                </div>
                
                <div class="metric">
                    <span>总设备数</span>
                    <span id="total-devices" class="metric-value">--</span>
                </div>
                
                <div class="metric">
                    <span>活跃报警</span>
                    <span id="active-alarms" class="metric-value">--</span>
                </div>
                
                <div class="metric">
                    <span>系统运行时间</span>
                    <span id="uptime" class="metric-value">--</span>
                </div>
            </div>
            
            <!-- 右侧功能区 -->
            <div>
                <div class="function-grid">
                    <a href="/device-manager" class="function-btn">
                        <span class="icon">🎛️</span>
                        <h3>设备配置</h3>
                        <p>管理设备连接和数据点</p>
                    </a>
                    
                    <a href="/device-config" class="function-btn">
                        <span class="icon">⚙️</span>
                        <h3>快速配置</h3>
                        <p>简易设备配置向导</p>
                    </a>
                    
                    <button class="function-btn" onclick="showDevices()">
                        <span class="icon">📱</span>
                        <h3>设备列表</h3>
                        <p>查看和管理连接的设备</p>
                    </button>
                    
                    <button class="function-btn" onclick="showAlarms()">
                        <span class="icon">🚨</span>
                        <h3>报警信息</h3>
                        <p>查看系统报警和事件</p>
                    </button>
                    
                    <button class="function-btn" onclick="showSystemStatus()">
                        <span class="icon">📊</span>
                        <h3>系统状态</h3>
                        <p>查看详细的系统信息</p>
                    </button>
                    
                    <button class="function-btn" onclick="showTasks()">
                        <span class="icon">⏰</span>
                        <h3>任务管理</h3>
                        <p>管理定时和调度任务</p>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 内容显示区域 -->
        <div class="content-area">
            <div id="welcome-content">
                <h2>欢迎使用工业物联网数据采集系统</h2>
                <p>这是一个专业的工业数据采集和监控系统，支持多种工业协议和设备。</p>
                
                <h3>主要功能特性</h3>
                <ul>
                    <li><strong>多协议支持</strong>：Modbus TCP/RTU、西门子S7、MQTT、OPC UA等主流工业协议</li>
                    <li><strong>高性能采集</strong>：多线程并发处理，支持500+设备同时连接，毫秒级采集频率</li>
                    <li><strong>多种存储</strong>：SQLite、MySQL、InfluxDB等多种数据库支持</li>
                    <li><strong>智能报警</strong>：阈值报警、状态变化报警、通信异常报警，支持多种通知方式</li>
                    <li><strong>灵活调度</strong>：支持定时任务、周期任务、Cron表达式调度</li>
                    <li><strong>RESTful API</strong>：完整的API接口，支持第三方系统集成</li>
                    <li><strong>容器化部署</strong>：支持Docker容器化部署，一键启动完整技术栈</li>
                </ul>
                
                <h3>系统架构</h3>
                <p>系统采用模块化设计，包含数据采集引擎、协议驱动、存储服务、报警服务、任务调度等核心组件，具备高可靠性、高性能和易扩展的特点。</p>
            </div>
            
            <div id="content-area" class="hidden">
                <div id="loading" class="loading hidden">
                    <h3>⏳ 加载中...</h3>
                    <p>正在获取数据，请稍候</p>
                </div>
                <div id="content-data"></div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentView = 'welcome';
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateSystemMetrics();
            // 每30秒更新一次系统指标
            setInterval(updateSystemMetrics, 30000);
        });
        
        // 更新系统指标
        async function updateSystemMetrics() {
            try {
                // 获取设备信息
                const devicesResponse = await fetch('/api/devices');
                if (devicesResponse.ok) {
                    const devicesData = await devicesResponse.json();
                    document.getElementById('total-devices').textContent = devicesData.total_count || 0;
                    document.getElementById('online-devices').textContent = devicesData.connected_count || 0;
                }
                
                // 获取报警信息
                const alarmsResponse = await fetch('/api/alarms');
                if (alarmsResponse.ok) {
                    const alarmsData = await alarmsResponse.json();
                    document.getElementById('active-alarms').textContent = 
                        Array.isArray(alarmsData) ? alarmsData.filter(a => a.status === 'active').length : 0;
                }
                
                // 获取系统状态
                const statusResponse = await fetch('/api/system/status');
                if (statusResponse.ok) {
                    const statusData = await statusResponse.json();
                    if (statusData.uptime) {
                        document.getElementById('uptime').textContent = formatUptime(statusData.uptime);
                    }
                }
            } catch (error) {
                console.error('更新系统指标失败:', error);
            }
        }
        
        // 格式化运行时间
        function formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            
            if (days > 0) {
                return `${days}天 ${hours}小时`;
            } else if (hours > 0) {
                return `${hours}小时 ${minutes}分钟`;
            } else {
                return `${minutes}分钟`;
            }
        }
        
        // 显示加载状态
        function showLoading() {
            document.getElementById('welcome-content').classList.add('hidden');
            document.getElementById('content-area').classList.remove('hidden');
            document.getElementById('loading').classList.remove('hidden');
            document.getElementById('content-data').innerHTML = '';
        }
        
        // 显示内容
        function showContent(html) {
            document.getElementById('loading').classList.add('hidden');
            document.getElementById('content-data').innerHTML = html;
        }
        
        // 显示错误
        function showError(message) {
            const errorHtml = `
                <div class="error">
                    <h3>❌ 加载失败</h3>
                    <p>${message}</p>
                    <button onclick="location.reload()" style="margin-top: 10px; padding: 8px 16px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        刷新页面
                    </button>
                </div>
            `;
            showContent(errorHtml);
        }
        
        // 显示设备列表
        async function showDevices() {
            if (currentView === 'devices') return;
            currentView = 'devices';
            
            showLoading();
            
            try {
                const response = await fetch('/api/devices');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                let html = '<h2>📱 设备列表</h2>';
                
                if (data.devices && data.devices.length > 0) {
                    html += `
                        <div style="margin-bottom: 20px;">
                            <span>总计: ${data.total_count} 台设备</span>
                            <span style="margin-left: 20px;">在线: ${data.connected_count} 台</span>
                        </div>
                    `;
                    
                    data.devices.forEach(device => {
                        const statusClass = device.connected ? 'status-connected' : 'status-disconnected';
                        const statusText = device.connected ? '在线' : '离线';
                        
                        html += `
                            <div class="device-card">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <h4 style="margin: 0 0 5px 0;">${device.device_name || 'Unknown'}</h4>
                                        <p style="margin: 0; color: #666;">${device.device_type || 'Unknown'} 协议</p>
                                    </div>
                                    <div class="device-status ${statusClass}">
                                        ${statusText}
                                    </div>
                                </div>
                                ${device.error ? `<p style="color: #f44336; margin-top: 10px;">错误: ${device.error}</p>` : ''}
                            </div>
                        `;
                    });
                } else {
                    html += '<p>暂无设备数据</p>';
                }
                
                showContent(html);
            } catch (error) {
                console.error('获取设备列表失败:', error);
                showError('无法加载设备列表: ' + error.message);
            }
        }
        
        // 显示报警信息
        async function showAlarms() {
            if (currentView === 'alarms') return;
            currentView = 'alarms';
            
            showLoading();
            
            try {
                const response = await fetch('/api/alarms');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                let html = '<h2>🚨 报警信息</h2>';
                
                if (Array.isArray(data) && data.length > 0) {
                    html += '<table>';
                    html += '<tr><th>时间</th><th>设备</th><th>类型</th><th>消息</th><th>状态</th></tr>';
                    
                    data.forEach(alarm => {
                        const statusClass = alarm.status === 'active' ? 'status-disconnected' : 'status-connected';
                        html += `
                            <tr>
                                <td>${alarm.timestamp || '--'}</td>
                                <td>${alarm.device_name || '--'}</td>
                                <td>${alarm.alarm_type || '--'}</td>
                                <td>${alarm.message || '--'}</td>
                                <td><span class="device-status ${statusClass}">${alarm.status || '--'}</span></td>
                            </tr>
                        `;
                    });
                    html += '</table>';
                } else {
                    html += '<p>当前没有报警信息</p>';
                }
                
                showContent(html);
            } catch (error) {
                console.error('获取报警信息失败:', error);
                showError('无法加载报警信息: ' + error.message);
            }
        }
        
        // 显示系统状态
        async function showSystemStatus() {
            if (currentView === 'status') return;
            currentView = 'status';
            
            showLoading();
            
            try {
                const response = await fetch('/api/system/status');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                let html = '<h2>📊 系统状态详情</h2>';
                
                // 基本信息
                html += '<h3>基本信息</h3>';
                html += '<table>';
                html += `<tr><td>系统状态</td><td><span class="device-status ${data.status === 'running' ? 'status-connected' : 'status-disconnected'}">${data.status || '未知'}</span></td></tr>`;
                html += `<tr><td>运行时间</td><td>${data.uptime ? formatUptime(data.uptime) : '--'}</td></tr>`;
                html += `<tr><td>版本</td><td>${data.version || 'v1.0.0'}</td></tr>`;
                html += `<tr><td>启动时间</td><td>${data.start_time || '--'}</td></tr>`;
                html += '</table>';
                
                // 服务状态
                if (data.services) {
                    html += '<h3>服务状态</h3>';
                    html += '<table>';
                    html += '<tr><th>服务</th><th>状态</th><th>描述</th></tr>';
                    Object.entries(data.services).forEach(([name, info]) => {
                        const statusClass = info.status === 'running' ? 'status-connected' : 'status-disconnected';
                        html += `
                            <tr>
                                <td>${name}</td>
                                <td><span class="device-status ${statusClass}">${info.status || '--'}</span></td>
                                <td>${info.description || '--'}</td>
                            </tr>
                        `;
                    });
                    html += '</table>';
                }
                
                // 性能指标
                if (data.metrics) {
                    html += '<h3>性能指标</h3>';
                    html += '<div class="function-grid">';
                    Object.entries(data.metrics).forEach(([key, value]) => {
                        html += `
                            <div class="metric">
                                <span>${key}</span>
                                <span class="metric-value">${value}</span>
                            </div>
                        `;
                    });
                    html += '</div>';
                }
                
                showContent(html);
            } catch (error) {
                console.error('获取系统状态失败:', error);
                showError('无法加载系统状态: ' + error.message);
            }
        }
        
        // 显示任务管理
        async function showTasks() {
            if (currentView === 'tasks') return;
            currentView = 'tasks';
            
            showLoading();
            
            try {
                const response = await fetch('/api/tasks');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                let html = '<h2>⏰ 任务管理</h2>';
                
                if (Array.isArray(data) && data.length > 0) {
                    html += '<table>';
                    html += '<tr><th>任务名称</th><th>类型</th><th>状态</th><th>下次执行</th><th>描述</th></tr>';
                    
                    data.forEach(task => {
                        const statusClass = task.status === 'running' ? 'status-connected' : 'status-disconnected';
                        html += `
                            <tr>
                                <td>${task.name || '--'}</td>
                                <td>${task.type || '--'}</td>
                                <td><span class="device-status ${statusClass}">${task.status || '--'}</span></td>
                                <td>${task.next_run || '--'}</td>
                                <td>${task.description || '--'}</td>
                            </tr>
                        `;
                    });
                    html += '</table>';
                } else {
                    html += '<p>当前没有活动任务</p>';
                }
                
                showContent(html);
            } catch (error) {
                console.error('获取任务列表失败:', error);
                showError('无法加载任务列表: ' + error.message);
            }
        }
    </script>
</body>
</html> 